<template>
  <!-- 这是地区下拉组件 -->
  <div class="comp-container">
    <div class="content-tree">
      <el-tree
        :data="regionData"
        :props="{
          label: 'name',
          children: 'childList'
        }"
        ref="tree"
        node-key="id"
        :highlight-current="true"
        :auto-expand-parent="true"
        :expand-on-click-node="false"
        :default-expanded-keys="treeExpandedKeys"
        :current-node-key="currentKey"
        @node-drag-start="handleDragStart"
        @node-drag-enter="handleDragEnter"
        @node-drag-leave="handleDragLeave"
        @node-drag-over="handleDragOver"
        @node-drag-end="handleDragEnd"
        @node-drop="handleDrop"
        @node-expand="handleExpand"
        @node-collapse="handleCollapse"
        @node-click="handleCurrentNode"
        draggable
        :allow-drop="allowDrop"
        :allow-drag="allowDrag">
        <div class="custom-tree-node" slot-scope="{ node, data }">
          <span class="tree-children" v-if="data.parentId != '0'">
            <i v-if="node.level<3" class="icon iconfont folder icon-folder-fill"></i>
          </span>
          <span class="tree-top" v-if="data.parentId == '0'">
            <i v-if="node.expanded" class="icon iconfont folder icon-folder-open"></i>
            <i v-else class="icon iconfont folder icon-folder-fill"></i>
          </span>
          <span class="region-title" :class="currentId===data.id?'titleActive':''">{{ data.name }}</span> 
          <span class="tree-children">
            <el-botton v-if="node.isCurrent" @click.stop="append(data)">
              <i class="icon iconfont active" :class="addIcon" ></i>
            </el-botton>
            <el-botton v-if="node.isCurrent && data.parentId !=='0'" @click.stop="remove(node, data)">
              <i class="icon iconfont active" :class="trashIcon"></i>
            </el-botton>
          </span>          
        </div>
      </el-tree>
    </div>
  </div>
</template>

<script>
// 设置一个新增默认的id
  import * as commonApi from '@/api/commonApi.js';
  export default {
    data(){
      return {
        regionData: [],
        addIcon: 'icon-add',
        trashIcon: 'icon-trash',
        currentId: '',
        treeExpandedKeys:[],
        removeNode:{},
        removeData:{},
        dialogVisible: false
      }
    },
    methods: {
      handleDrop(draggingNode, dropNode) {
        const childNodeList = dropNode.parent.childNodes;
        let updateList = [];
        for(let i=0; i<childNodeList.length; i++){
          updateList.push({id:childNodeList[i].data.id, sortBy: i+1})
        }
        commonApi.updateRegionSort(updateList).then( res=> {
          if(res.data.statusCode == '200'){
            this.getRegionList();  
          } else {
            if(res.data.msg.length > 20){
              self.$message.error('服务器接口异常，请联系管理员');
            } else {
              self.$message.error(res.data.msg);
            }
          }
        });
      },
      allowDrop(draggingNode, dropNode, type){
        if(draggingNode.level === dropNode.level){
            if(draggingNode.parent.id === dropNode.parent.id){
                return type === 'prev' || type === 'next'
            }
        }
    },
      handleExpand(data){
        this.treeExpandedKeys.push(data.id);
      },
      handleCollapse(data){
        const index = this.treeExpandedKeys.indexOf(data.id);
          if (index > -1) {
              this.treeExpandedKeys.splice(index, 1);
          }
      },
      handleCurrentNode(data, node){
        console.log('type',data.type)
        let formData = {};
        if(data.type==='add'){
          formData = {
            parentId: data.parentId=='0'? '0' :node.parent.data.id,
              parentName: data.parentId=='0'? '0' :node.parent.data.name,
              parentFullName: data.parentId=='0'? '0' :node.parent.data.fullName,
              name: data.name,
              fullRegion: data.fullName,
              code: data.code,
              sortBy: data.sortBy,
              type: data.type
          };
          this.$emit('appEvent',formData);
        } else {
          this.currentId = data.id;
          commonApi.getRegionDetails({id: data.id}).then(res => {
          if(res.data.statusCode == '200'){
            const resData = res.data.data;
            // 封装回传数据
            formData = {
              parentId: data.parentId=='0'? '0' :node.parent.data.id,
              parentName: data.parentId=='0'? '0' :node.parent.data.name,
              parentFullName: data.parentId=='0'? '0' :node.parent.data.fullName,
              id: data.id,
              name: data.name,
              fullRegion: data.fullName,
              code: data.code,
              sortBy: data.sortBy,
              remarks: resData.remarks || '',
              type: data.type || 'edit'
            }
            this.$emit('appEvent',formData);
            } else {
              if(res.data.msg.length > 20){
                this.$message.error('服务器接口异常，请联系管理员');
              } else {
                this.$message.error(res.data.msg);
              }
            }
          });
        }  
      },
      // 新增节点
      append(data) {
        let id = Math.random().toString(36).substr(-8);
        let sort = data.childNumber+1;
        const newChild = { id: id, sortBy: sort,name: '新建节点', type:'add', childList: [] };
        if (!data.childList) {
          this.$set(data, 'childList', []);
        }
        data.childList.push(newChild);
        const params = {
          parentId: data.id,
          parentName: data.name,
          parentFullName: data.fullName,
          name: '新建节点',
          sortBy: sort
        }
        this.$emit('appendEvent',params);
      },
      // 删除节点
      remove(node, data) {
        this.dialogVisible = false;
        if(data.childNumber>0){
            this.$confirm('是否删除该地区及其子地区？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then( async () => {
              const parent = node.parent;
              const children = parent.data.childList || parent.data;
              const index = children.findIndex(d => d.id === data.id);
              children.splice(index, 1);
              // 确保删除的节点是已经提交过的节点
              if(data.code){
                this.deleteRegion(data.id);
              } 
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              });          
            });
          } else {
            this.$confirm('是否删除该地区？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then( async () => {
              const parent = node.parent;
              const children = parent.data.childList || parent.data;
              const index = children.findIndex(d => d.id === data.id);
              children.splice(index, 1);
              // 确保删除的节点是已经提交过的节点
              if(data.code){
                this.deleteRegion(data.id);
              } 
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              });          
            });
          }
      },
      // 删除指定节点
      deleteRegion(id){
        commonApi.deleteRegion({id: id}).then( res=> {
          if(res.data.statusCode == '200'){
              this.getRegionList()
              this.$message({
              type: 'success',
              message: '删除成功!'
            });
          } else {
            if(res.data.msg.length > 20){
              this.$message.error('服务器接口异常，请联系管理员');
            } else {
              this.$message.error(res.data.msg);
            }
          }
        })
      },
      // 获取完整的地区树
    getRegionList(){
        commonApi.getRegionList({id:'d21bb23e29614a1e95b5d537ccbfbf66'}).then( res=> {
            if(res.data.statusCode == '200'){
                this.regionData = [res.data.data];   
            } else {
                if(res.data.msg.length > 20){
                this.$message.error('服务器接口异常，请联系管理员');
              } else {
                this.$message.error(res.data.msg);
              }
            }
        })
      }
    },
    created(){
      this.getRegionList();
      this.treeExpandedKeys = ['97b5f2428e45429c875782715e06888b'];
    }
  }
</script>

<style>
  .content-tree {
    max-width: 600px;
    height: 540px;
    border: 1px solid #ddd;
    border-radius: 5px;
    padding: 1rem;
    overflow-y: auto;
    box-sizing: border-box;
  }
  /* .el-tree-node__expand-icon {
    display: none;
  } */
  .custom-tree-node {
    font-size: 14px;
  }
  .custom-tree-node .folder {
    color: #ffa007;
    margin-right: 2px;
  }
  .tree-children i{
    font-size: 14px !important;
    margin-right: 4px;
  }
  .active {
    color: #409EFF;
    margin: 0 10px;
  }
  .region-title:hover {
        color: #1492ff;
  }
  .titleActive {
    color: #409EFF;
  }
</style> 